# MySQL服务管理脚本
# 用于检查、启动和配置MySQL服务的自动化脚本

param(
    [string]$Action = "check",  # check, start, configure, install-watchdog
    [string]$ServiceName = "MySQL80"
)

# 需要管理员权限的函数
function Test-AdminRights {
    $currentUser = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = New-Object Security.Principal.WindowsPrincipal($currentUser)
    return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

# 检查MySQL服务状态
function Check-MySQLService {
    param([string]$ServiceName)
    
    $service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
    if (-not $service) {
        Write-Host "❌ 未找到MySQL服务: $ServiceName" -ForegroundColor Red
        return $null
    }
    
    Write-Host "📊 MySQL服务状态: $($service.Status)" -ForegroundColor Cyan
    Write-Host "📊 启动类型: $(Get-CimInstance -ClassName Win32_Service -Filter "Name='$ServiceName'").StartMode" -ForegroundColor Cyan
    
    return $service
}

# 启动MySQL服务
function Start-MySQLService {
    param([string]$ServiceName)
    
    if (-not (Test-AdminRights)) {
        Write-Host "❌ 需要管理员权限来启动MySQL服务" -ForegroundColor Red
        Write-Host "请以管理员身份运行PowerShell，然后执行:" -ForegroundColor Yellow
        Write-Host "  sc start $ServiceName" -ForegroundColor Yellow
        return $false
    }
    
    try {
        Write-Host "🔄 正在启动MySQL服务..." -ForegroundColor Yellow
        Start-Service -Name $ServiceName -ErrorAction Stop
        Start-Sleep -Seconds 3
        
        $service = Get-Service -Name $ServiceName
        if ($service.Status -eq 'Running') {
            Write-Host "✅ MySQL服务启动成功" -ForegroundColor Green
            return $true
        } else {
            Write-Host "❌ MySQL服务启动失败，当前状态: $($service.Status)" -ForegroundColor Red
            return $false
        }
    } catch {
        Write-Host "❌ 启动MySQL服务时发生错误: $($_.Exception.Message)" -ForegroundColor Red
        return $false
    }
}

# 配置MySQL服务为自动启动
function Configure-MySQLService {
    param([string]$ServiceName)
    
    if (-not (Test-AdminRights)) {
        Write-Host "❌ 需要管理员权限来配置MySQL服务" -ForegroundColor Red
        Write-Host "请以管理员身份运行PowerShell，然后执行此脚本" -ForegroundColor Yellow
        return $false
    }
    
    try {
        Write-Host "🔧 配置MySQL服务为自动启动..." -ForegroundColor Yellow
        
        # 设置服务为自动启动
        Set-Service -Name $ServiceName -StartupType Automatic -ErrorAction Stop
        
        # 设置服务失败时自动重启
        sc.exe failure $ServiceName reset= 86400 actions= restart/60000/restart/60000/restart/60000
        
        # 设置服务描述
        sc.exe description $ServiceName "MySQL Database Server - Auto-configured for development"
        
        Write-Host "✅ MySQL服务配置完成:" -ForegroundColor Green
        Write-Host "   - 启动类型: 自动" -ForegroundColor Green
        Write-Host "   - 失败恢复: 自动重启" -ForegroundColor Green
        
        return $true
    } catch {
        Write-Host "❌ 配置MySQL服务时发生错误: $($_.Exception.Message)" -ForegroundColor Red
        return $false
    }
}

# 安装MySQL监控守护进程
function Install-MySQLWatchdog {
    param([string]$ServiceName)
    
    $watchdogScript = @"
# MySQL监控守护脚本
# 每30秒检查一次MySQL服务状态，如果停止则尝试重启

`$serviceName = "$ServiceName"
`$logFile = "E:\DEV_VISION\logs\mysql_watchdog.log"

# 创建日志目录
`$logDir = Split-Path `$logFile -Parent
if (-not (Test-Path `$logDir)) {
    New-Item -ItemType Directory -Path `$logDir -Force | Out-Null
}

function Write-Log {
    param([string]`$Message)
    `$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    `$logEntry = "[$timestamp] `$Message"
    Write-Host `$logEntry
    Add-Content -Path `$logFile -Value `$logEntry
}

Write-Log "MySQL监控守护进程启动"

while (`$true) {
    try {
        `$service = Get-Service -Name `$serviceName -ErrorAction SilentlyContinue
        
        if (-not `$service) {
            Write-Log "警告: 未找到MySQL服务 `$serviceName"
        } elseif (`$service.Status -ne 'Running') {
            Write-Log "检测到MySQL服务已停止，尝试重启..."
            
            try {
                Start-Service -Name `$serviceName -ErrorAction Stop
                Start-Sleep -Seconds 2
                `$service.Refresh()
                
                if (`$service.Status -eq 'Running') {
                    Write-Log "MySQL服务重启成功"
                } else {
                    Write-Log "MySQL服务重启失败，状态: `$(`$service.Status)"
                }
            } catch {
                Write-Log "重启MySQL服务时发生错误: `$(`$_.Exception.Message)"
            }
        }
    } catch {
        Write-Log "监控过程中发生错误: `$(`$_.Exception.Message)"
    }
    
    Start-Sleep -Seconds 30
}
"@
    
    $watchdogPath = "E:\DEV_VISION\scripts\mysql_watchdog.ps1"
    Set-Content -Path $watchdogPath -Value $watchdogScript -Encoding UTF8
    
    Write-Host "✅ MySQL监控守护脚本已创建: $watchdogPath" -ForegroundColor Green
    Write-Host "💡 要启动监控，请在新的PowerShell窗口中运行:" -ForegroundColor Yellow
    Write-Host "   powershell -ExecutionPolicy Bypass -File `"$watchdogPath`"" -ForegroundColor Yellow
}

# 主逻辑
switch ($Action.ToLower()) {
    "check" {
        Check-MySQLService -ServiceName $ServiceName
    }
    "start" {
        $service = Check-MySQLService -ServiceName $ServiceName
        if ($service -and $service.Status -ne 'Running') {
            Start-MySQLService -ServiceName $ServiceName
        } elseif ($service) {
            Write-Host "✅ MySQL服务已在运行中" -ForegroundColor Green
        }
    }
    "configure" {
        Configure-MySQLService -ServiceName $ServiceName
    }
    "install-watchdog" {
        Install-MySQLWatchdog -ServiceName $ServiceName
    }
    default {
        Write-Host "用法: mysql_service_manager.ps1 -Action [check|start|configure|install-watchdog]" -ForegroundColor Yellow
    }
}
